package models

import (
	db "goORMTest/goJdbcTest/database"
	_ "log"
)

type PersonDo struct {
	Id        int    `json:"id" form:"id"`
	FirstName string `json:"first_name" form:"first_name"`
	LastName  string `json:"last_name" form:"last_name"`
}

func (p *PersonDo) AddPerson() (id int64, err error) {
	rs, err := db.SqlDB.Exec("INSERT INTO tb_person(first_name, last_name) VALUES (?, ?)", p.FirstName, p.LastName)
	if err != nil {
		return
	}
	id, err = rs.LastInsertId()
	return
}
func (p *PersonDo) GetPersons() (persons []PersonDo, err error) {
	persons = make([]PersonDo, 0)
	rows, err := db.SqlDB.Query("SELECT id, first_name, last_name FROM person")
	defer rows.Close()
	if err != nil {
		return
	}
	for rows.Next() {
		var person PersonDo
		rows.Scan(&person.Id, &person.FirstName, &person.LastName)
		persons = append(persons, person)
	}
	if err = rows.Err(); err != nil {
		return
	}
	return
}
func (p *PersonDo) GetPerson(id int) (person PersonDo, err error) {
	// 字符串转str
	//idstr := strconv.Itoa(id)
	sql := "SELECT id, first_name, last_name FROM tb_person where id=?"
	rows, err := db.SqlDB.Query(sql, id)
	defer rows.Close()
	if err != nil {
		return
	}
	for rows.Next() {
		rows.Scan(&person.Id, &person.FirstName, &person.LastName)
		break
	}
	if err = rows.Err(); err != nil {
		return
	}
	return
}
